import React, { useState } from 'react';
import { Card, Tabs, Form, Input, Select, Button, Table, Space, Tag, Modal, Upload, message } from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined, UploadOutlined, DownloadOutlined, PlayCircleOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { useParams } from 'react-router-dom';
import './styles.css';

const { TabPane } = Tabs;
const { TextArea } = Input;
const { Option } = Select;

// 定时任务选项
const scheduleOptions = [
  { value: 'manual', label: '手动执行' },
  { value: 'every_hour', label: '每小时' },
  { value: 'every_day', label: '每天' },
  { value: 'every_week', label: '每周' },
  { value: 'every_month', label: '每月' },
  { value: 'custom', label: '自定义cron' }
];

// 模拟规则集数据
const mockRuleSets = [
  {
    id: 1,
    name: '敏感数据识别规则',
    description: '识别个人信息、金融数据等敏感数据',
    type: 'detection',
    status: 'active',
    priority: 'high',
    schedule: 'every_day',
    script: `import pandas as pd
import numpy as np

def detect_sensitive_info(df):
    # 示例：检测身份证、手机号、邮箱等敏感信息
    sensitive_patterns = {
        'id_card': r'\\d{17}[0-9X]',
        'phone': r'1\\d{10}',
        'email': r'[\\w.-]+@[\\w.-]+\\.[\\w.-]+'
    }
    
    results = pd.DataFrame()
    for col in df.columns:
        for pattern_name, pattern in sensitive_patterns.items():
            matches = df[col].astype(str).str.contains(pattern, na=False)
            if matches.any():
                results = pd.concat([results, pd.DataFrame({
                    'column': col,
                    'pattern_type': pattern_name,
                    'match_count': matches.sum()
                }, index=[0])])
    
    return results`,
  },
  {
    id: 2,
    name: '数据加密规则',
    description: '对敏感数据进行加密处理',
    type: 'protection',
    status: 'active',
    priority: 'high',
    schedule: 'every_hour',
    script: `import pandas as pd
import hashlib

def encrypt_sensitive_data(df):
    # 示例：对敏感字段进行哈希加密
    sensitive_columns = ['id_card', 'phone', 'email']
    
    df_encrypted = df.copy()
    for col in sensitive_columns:
        if col in df.columns:
            df_encrypted[col] = df[col].apply(lambda x: 
                hashlib.sha256(str(x).encode()).hexdigest() if pd.notna(x) else x)
    
    return df_encrypted`,
  },
  {
    id: 3,
    name: '访问控制规则',
    description: '控制数据访问权限',
    type: 'control',
    status: 'active',
    priority: 'medium',
    schedule: 'manual',
    script: `import pandas as pd

def apply_access_control(df, user_level):
    # 示例：根据用户级别过滤敏感数据
    sensitivity_levels = {
        'id_card': 3,
        'phone': 2,
        'email': 1
    }
    
    df_filtered = df.copy()
    for col, level in sensitivity_levels.items():
        if col in df.columns and user_level < level:
            df_filtered = df_filtered.drop(columns=[col])
    
    return df_filtered`,
  },
];

const defaultPythonScript = `import pandas as pd
import numpy as np

def process_data(df):
    # 在这里添加数据处理逻辑
    # 例如：数据清洗、特征提取、风险计算等
    return df

def main():
    # 读取数据
    df = pd.read_csv('input_data.csv')
    
    # 处理数据
    results = process_data(df)
    
    # 保存结果
    results.to_csv('output_results.csv', index=False)

if __name__ == '__main__':
    main()`;

const RuleConfig: React.FC = () => {
  const { id } = useParams();
  const [activeTab, setActiveTab] = useState('1');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingRule, setEditingRule] = useState<any>(null);
  const [pythonScript, setPythonScript] = useState(defaultPythonScript);
  const [customCron, setCustomCron] = useState('');
  const [form] = Form.useForm();

  const ruleSetColumns = [
    {
      title: '规则名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => <Tag color="blue">{type}</Tag>,
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      render: (priority: string) => {
        const colors = {
          high: 'red',
          medium: 'orange',
          low: 'green',
        };
        return <Tag color={colors[priority as keyof typeof colors]}>{priority.toUpperCase()}</Tag>;
      },
    },
    {
      title: '定时任务',
      dataIndex: 'schedule',
      key: 'schedule',
      render: (schedule: string) => {
        const option = scheduleOptions.find(opt => opt.value === schedule);
        return (
          <Tag icon={<ClockCircleOutlined />} color="purple">
            {option?.label || schedule}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEditRule(record)}>
            编辑
          </Button>
          <Button type="link" danger icon={<DeleteOutlined />}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleAddRule = () => {
    setEditingRule(null);
    setPythonScript(defaultPythonScript);
    setIsModalVisible(true);
  };

  const handleEditRule = (rule: any) => {
    setEditingRule(rule);
    setPythonScript(rule.script || defaultPythonScript);
    setCustomCron(rule.schedule === 'custom' ? rule.cronExpression : '');
    form.setFieldsValue({
      name: rule.name,
      description: rule.description,
      type: rule.type,
      priority: rule.priority,
      schedule: rule.schedule,
      cronExpression: rule.cronExpression,
    });
    setIsModalVisible(true);
  };

  const handleModalOk = () => {
    form.validateFields().then((values) => {
      console.log('Form values:', values);
      console.log('Python script:', pythonScript);
      setIsModalVisible(false);
      form.resetFields();
    });
  };

  const handleScriptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setPythonScript(e.target.value);
  };

  const handleRunScript = () => {
    message.success('开始执行 Python 脚本');
    // 这里添加实际的脚本执行逻辑
  };

  const handleDownloadResults = () => {
    message.success('开始下载结果集');
    // 这里添加实际的结果下载逻辑
  };

  return (
    <div className="rule-config">
      <Card title="监管模型配置">
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="基本信息" key="1">
            <Form layout="vertical">
              <Form.Item label="模型名称" required>
                <Input placeholder="请输入模型名称" />
              </Form.Item>
              <Form.Item label="描述">
                <TextArea rows={4} placeholder="请输入模型描述" />
              </Form.Item>
              <Form.Item label="类型" required>
                <Select placeholder="请选择模型类型">
                  <Option value="privacy">隐私保护</Option>
                  <Option value="audit">交易审计</Option>
                  <Option value="compliance">合规监管</Option>
                  <Option value="quality">质量监控</Option>
                  <Option value="risk">风险防控</Option>
                </Select>
              </Form.Item>
              <Form.Item label="风险等级" required>
                <Select placeholder="请选择风险等级">
                  <Option value="high">高</Option>
                  <Option value="medium">中</Option>
                  <Option value="low">低</Option>
                </Select>
              </Form.Item>
            </Form>
          </TabPane>
          <TabPane tab="规则集配置" key="2">
            <div style={{ marginBottom: 16 }}>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAddRule}>
                添加规则
              </Button>
            </div>
            <Table columns={ruleSetColumns} dataSource={mockRuleSets} rowKey="id" />
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title={editingRule ? "编辑规则" : "添加规则"}
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={1000}
        style={{ top: 20 }}
      >
        <Form form={form} layout="vertical">
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本信息" key="1">
              <Form.Item
                name="name"
                label="规则名称"
                rules={[{ required: true, message: '请输入规则名称' }]}
              >
                <Input placeholder="请输入规则名称" />
              </Form.Item>
              <Form.Item name="description" label="描述">
                <TextArea rows={4} placeholder="请输入规则描述" />
              </Form.Item>
              <Form.Item
                name="type"
                label="类型"
                rules={[{ required: true, message: '请选择规则类型' }]}
              >
                <Select placeholder="请选择规则类型">
                  <Option value="detection">检测</Option>
                  <Option value="protection">保护</Option>
                  <Option value="control">控制</Option>
                </Select>
              </Form.Item>
              <Form.Item
                name="priority"
                label="优先级"
                rules={[{ required: true, message: '请选择优先级' }]}
              >
                <Select placeholder="请选择优先级">
                  <Option value="high">高</Option>
                  <Option value="medium">中</Option>
                  <Option value="low">低</Option>
                </Select>
              </Form.Item>
              <Form.Item
                name="schedule"
                label="定时任务"
                rules={[{ required: true, message: '请选择定时任务类型' }]}
              >
                <Select
                  placeholder="请选择定时任务类型"
                  onChange={(value) => {
                    if (value !== 'custom') {
                      form.setFieldsValue({ cronExpression: undefined });
                    }
                  }}
                >
                  {scheduleOptions.map(option => (
                    <Option key={option.value} value={option.value}>{option.label}</Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, currentValues) => prevValues.schedule !== currentValues.schedule}
              >
                {({ getFieldValue }) => 
                  getFieldValue('schedule') === 'custom' ? (
                    <Form.Item
                      name="cronExpression"
                      label="Cron表达式"
                      rules={[{ required: true, message: '请输入Cron表达式' }]}
                    >
                      <Input placeholder="例如: 0 0 * * * (每天零点执行)" />
                    </Form.Item>
                  ) : null
                }
              </Form.Item>
            </TabPane>
            <TabPane tab="Python脚本" key="2">
              <Form.Item label="数据源配置">
                <Select defaultValue="mysql" style={{ width: '200px', marginBottom: '16px' }}>
                  <Option value="mysql">MySQL数据库</Option>
                </Select>
                <Input placeholder="请输入数据源JDBC" style={{ marginBottom: '16px' }} />
              </Form.Item>
              <Form.Item label="脚本内容">
                <TextArea
                  rows={15}
                  value={pythonScript}
                  onChange={handleScriptChange}
                  className="python-editor"
                />
              </Form.Item>
            </TabPane>
          </Tabs>
        </Form>
      </Modal>
    </div>
  );
};

export default RuleConfig; 